<!-- 
    *名称：弹窗的搜索条件组件
    *功能：methods
      1.点击搜索的方法：@search
      2.搜索条件 props : formItemList
-->
<template>
  <div class="canSeeWindow" :style="{ maxHeight: isOpen ? '9999px' : showHeight + 'px' }">
    <div class="dialog-search">
      <el-form :inline="true" id="content" ref="ruleForm" :model="formInline" class="demo-form-inline from-maxbox">
        <slot></slot>
        <el-form-item label-position="left" v-for="(item, index) in formItemList" :key="index" :label="item.label" class="from-list">
          <!-- 小于等于3的radioGroup -->
          <div v-if="item.type == 'radio_select'" class="radio_select">
            <el-radio-group @change="change" v-if="item.selectOptions.length <= 3" v-model="formInline[item.param]" size="small">
              <el-radio-button v-for="item2 in item.selectOptions" v-if="item2.show === undefined || item2.show == true" :label="item2.value">{{ item2.name }}</el-radio-button>
            </el-radio-group>
            <el-select v-else v-model="formInline[item.param]" :placeholder="item.placeholder || '请选择'" size="mini" filterable clearable @keyup.enter.native="onSubmit">
              <el-option v-for="(item2, index2) in item.selectOptions" :key="index2" :label="item2.name" :value="item2.value"></el-option>
            </el-select>
          </div>

          <!-- 下拉框单选 -->
          <el-select v-if="item.type == 'select'" v-model="formInline[item.param]" :placeholder="item.placeholder || '请选择'" size="mini" filterable clearable @keyup.enter.native="onSubmit">
            <el-option v-for="(item2, index2) in item.selectOptions" :key="index2" :label="item2.name" :value="item2.value"></el-option>
          </el-select>
          <!-- 下拉框可以多选 -->
          <el-select v-if="item.type == 'multiple'" v-model="formInline[item.param]" :placeholder="item.placeholder || '请选择'" size="mini" multiple filterable collapse-tags @keyup.enter.native="onSubmit">
            <el-option v-for="(item2, index2) in item.selectOptions" :key="index2" :label="item2.name" :value="item2.value"></el-option>
          </el-select>
          <!-- 输入框 -->
          <el-input v-if="item.type == 'input'" v-model="formInline[item.param]" size="mini" :placeholder="item.placeholder || '请输入'" @keyup.enter.native="onSubmit">
          </el-input>
          <!-- 输入框输数字 -->
          <el-input v-if="item.type == 'inputNumber'" v-model="formInline[item.param]" size="mini" type="number" :placeholder="item.placeholder || '请输入'" @keyup.enter.native="onSubmit">
          </el-input>
          <!-- 输入框下拉框组合 -->
          <div class="sele-box">
            <el-input v-if="item.type == 'seletmin'" placeholder="请输入内容" v-model="formInline[item.param]" class="input-with-select" @keyup.enter.native="onSubmit">
              <el-select v-model="formInline[item.selevalue]" slot="prepend" placeholder="请选择" class="sele-one">
                <el-option v-for="(item2, index2) in item.selectOptions" :key="index2" :label="item2.name" :value="item2.value"></el-option>
              </el-select>
            </el-input>
          </div>
          <div class="dateRange" v-if="item.type == 'datetime'">
            <el-date-picker v-model="formInline[item.param]" type="datetime" :placeholder="item.placeholder || '选择时间'" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" class="picker-tiem" @keyup.enter.native="onSubmit">
            </el-date-picker>
          </div>
          <!-- 日期选择器 -->
          <div class="dateRange" v-if="item.type == 'dateRange'">
            <el-date-picker v-model="formInline[item.param1]" type="datetime" :placeholder="item.placeholder || '开始时间'" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" class="picker-tiem" @keyup.enter.native="onSubmit">
            </el-date-picker>
            <span class="tiem-span">~</span>
            <el-date-picker v-model="formInline[item.param2]" type="datetime" :placeholder="item.placeholder || '结束时间'" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" class="picker-tiem" @keyup.enter.native="onSubmit" default-time="23:59:59">
            </el-date-picker>
          </div>
          <!-- 年龄 -->
          <el-input v-if="item.type == 'ageIpt1'" v-model="formInline[item.param]" size="mini" :placeholder="item.placeholder || '请输入'" @keyup.enter.native="onSubmit" class="picker-tiem">
          </el-input>
          <span v-if="item.type == 'ageIpt2'" class="tiem-span">~</span>
          <el-input v-if="item.type == 'ageIpt2'" v-model="formInline[item.param]" size="mini" :placeholder="item.placeholder || '请输入'" @keyup.enter.native="onSubmit" class="picker-tiem">
          </el-input>
          <!-- 下拉框 年月 -->
          <el-select v-if="item.type == 'yearSelect'" v-model="formInline[item.param]" :placeholder="item.placeholder" size="mini" class="year-selet" @keyup.enter.native="onSubmit">
            <el-option v-for="(item2, index2) in item.selectOptions" :key="index2" :label="item2.name" :value="item2.value"></el-option>
          </el-select>
          <!-- 级联选择省市区 -->
          <el-cascader v-if="item.type == 'province'" placeholder="请选择省/市/区" v-model="formInline[item.param]" :options="mapAllDatas" filterable :props="optionProps" @keyup.enter.native="onSubmit"></el-cascader>
          <!-- 下拉框 省市区 -->
          <el-select v-if="item.type == 'provinceThree'" v-model="formInline[item.param]" placeholder="请选择省" size="mini" @change="provinceChange" class="pro-box" @keyup.enter.native="onSubmit">
            <el-option v-for="(item, index) in provinceArr" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-if="item.type == 'cityThree'" v-model="formInline[item.param]" placeholder="市" size="mini" @change="cityChange" class="pro-box" @keyup.enter.native="onSubmit">
            <el-option v-for="(item, index) in cityArr" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-if="item.type == 'areaThree'" v-model="formInline[item.param]" placeholder="区" size="mini" @change="areaChange" class="pro-box" @keyup.enter.native="onSubmit">
            <el-option v-for="(item, index) in areaArr" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!--  -->
        <el-form-item :class="resetSearch ? 'active' : ''" v-if="isOpen && contentHeight > showHeight">
          <div style="padding-left: 10px" v-if="resetSearch">
            <el-button type="primary" @click="isOpen = !isOpen" class="filterSwitch">{{ isOpen ? "收起" : "展开" }}
              <img class="filterImg" src="@/assets/img/filterClose.png" alt="" />
            </el-button>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button class="operation_btn1" size="mini" @click="resetForm('ruleForm')">重置</el-button>
          </div>
          <div style="padding-left: 10px" v-else>
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </div>
        </el-form-item>

        <!-- 可用于显示其他按钮 -->
        <div class="action" :class="resetSearch ? 'active' : ''" v-if="!isOpen || contentHeight <= showHeight">
          <div class="action_box" style="padding-left: 10px" v-if="resetSearch">
            <el-button class="filterSwitch" type="primary" @click="isOpen = !isOpen" v-if="contentHeight > showHeight">{{ "展开" }}
              <img class="filterImg" src="@/assets/img/filterOpen.png" alt="" />
            </el-button>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button class="operation_btn1" size="mini" @click="resetForm('ruleForm')">重置</el-button>
          </div>
          <div style="padding-left: 10px" v-else>
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </div>
          <slot name="action"></slot>
        </div>
      </el-form>
    </div>
    <div class="block" :style="{ width: isOpen ? '0' : contentHeight > showHeight ? '215px' : '115px' }"></div>
  </div>
</template>

<script>
export default {
  name: "searchCondition",
  props: {
    emitSearch: {
      // 是否立即执行搜索
      type: Boolean,
      default: false,
    },
    resetSearch: {
      // 是否展示搜索按钮
      type: Boolean,
      default: false,
    },
    formItemList: {
      type: Array,
      default() {
        return [
          {
            label: "下拉框",
            type: "select",
            selectOptions: [{ name: 111, value: 111 }],
            param: "company",
            defaultSelect: "222", // 下拉框默认选中项
          },
          {
            label: "输入框",
            type: "input",
            param: "name",
          },
        ]
      },
    },
    showHeight: {
      type: Number,
      default: 43,
    },
  },
  mounted() {
    // 防止某些兼容问题因此减2
    this.contentHeight = document.getElementById("content").clientHeight - 2
    if (this.contentHeight > this.showHeight) {
      this.$nextTick(() => {
        this.isOpen = this.contentHeight <= this.showHeight
      })
    }
  },
  activated() {
    // 当前页面时加入监听器
    window.addEventListener("resize", this.changeOpen)
  },
  deactivated() {
    // 离开时移除监听器
    window.removeEventListener("resize", this.changeOpen)
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.changeOpen)
  },
  data() {
    let formInline = {}
    for (const obj of this.formItemList) {
      if (obj.param) {
        formInline[obj.param] = obj.defaultSelect || ""
      }
      if (obj.type == "province") {
        this.getCityList()
      }
      if (obj.type == "provinceThree") {
        this.getprovince()
      }
    }
    return {
      showOpen: false,
      isOpen: false,
      formInline,
      mapAllDatas: [],
      optionProps: {
        //配置节点
        value: "name",
        label: "name",
        children: "children",
      },
      provinceArr: [],
      cityArr: [],
      areaArr: [],
      contentHeight: undefined,
    }
  },
  watch: {
    emitSearch(newVal, oldVal) {
      // 是否立即触发搜索  用在弹窗中异步请求下拉框后  或者给下拉框赋值默认值后  需要用到这个方法
      if (newVal) {
        console.log("此时触发--立即执行搜索")

        this.$emit("search", this.formInline)
      }
    },
    formItemList: {
      handler(newVal, oldVal) {
        for (const obj of this.formItemList) {
          if (obj.defaultSelect || obj.defaultSelect == "" || obj.defaultSelect == 0) {
            if (obj.param) {
              this.formInline[obj.param] = obj.defaultSelect
            }
          }
        }
        this.formInline = {
          ...this.formInline,
        }
        // console.log("监听器", this.formItemList, this.formInline)
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    changeOpen() {
      // 防止某些浏览器兼容问题因此减2
      this.contentHeight = document.getElementById("content").clientHeight - 2
    },
    change(e) {
      console.log(e)
    },
    open() { },
    onSubmit() {
      this.$emit("search", this.formInline)
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      let formInline = {}
      for (const obj of this.formItemList) {
        // formInline[obj.param] = obj.defaultSelect || "";  // 重置时下拉框的默认值如果要保留就选用这个
        if (obj.param) {
          formInline[obj.param] = "" // 所有筛选条件清空
        }
      }

      this.formInline = formInline
      this.cityArr = []
      this.areaArr = []
      this.$emit("reset")
      this.$emit("search", this.formInline)
    },
    //获取省市区三级树形的数据
    async getCityList() {
      try {
        let res = await this.request({
          url: "/text/getCityAll",
          method: "get",
          loading: false,
          data: {
            is_letter: 2, //是否需要首字母 1 需要 2 不需要（默认不需要，可不传此参数）
            parent_id: "", //父级id
            is_tree: 1, //是否返回省市区三级树形结构 1是 2否 属性结构只能返回 3 级，若需要街道，获取到省市区后，在根据父级id，获取街道
          },
        })
        if (res) {
          this.mapAllDatas = res.content
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    //获取省市区的数据 3个下拉框
    async getprovince() {
      try {
        let res = await this.request({
          url: "/text/getCityAll",
          method: "get",
          loading: false,
          data: {
            is_letter: 2, //是否需要首字母 1 需要 2 不需要（默认不需要，可不传此参数）
            parent_id: "", //父级id
            is_tree: 2, //是否返回省市区三级树形结构 1是 2否 属性结构只能返回 3 级，若需要街道，获取到省市区后，在根据父级id，获取街道
          },
        })
        if (res) {
          this.provinceArr = res.content
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    async provinceChange(value) {
      console.log(value)
      try {
        let res = await this.request({
          url: "/text/getCityAll",
          method: "get",
          loading: false,
          data: {
            is_letter: 2, //是否需要首字母 1 需要 2 不需要（默认不需要，可不传此参数）
            parent_id: value, //父级id
            is_tree: 2, //是否返回省市区三级树形结构 1是 2否 属性结构只能返回 3 级，若需要街道，获取到省市区后，在根据父级id，获取街道
          },
        })
        if (res) {
          this.formInline.city = ""
          this.formInline.area = ""
          this.areaArr = []
          this.cityArr = res.content
          this.provinceArr.map((item) => {
            if (item.id === value) {
              this.formInline.province = item.name
            }
          })
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    async cityChange(value) {
      try {
        let res = await this.request({
          url: "/text/getCityAll",
          method: "get",
          loading: false,
          data: {
            is_letter: 2, //是否需要首字母 1 需要 2 不需要（默认不需要，可不传此参数）
            parent_id: value, //父级id
            is_tree: 2, //是否返回省市区三级树形结构 1是 2否 属性结构只能返回 3 级，若需要街道，获取到省市区后，在根据父级id，获取街道
          },
        })
        if (res) {
          this.formInline.area = ""
          this.areaArr = []
          this.areaArr = res.content
          this.cityArr.map((item) => {
            if (item.id === value) {
              this.formInline.city = item.name
            }
          })
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    areaChange(value) {
      this.areaArr.map((item) => {
        if (item.id === value) {
          this.formInline.area = item.name
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
<style lang="scss">
.filterSwitch {
  width: 66px;
  height: 32px;
  // ::v-deep(.el-button--small) {
  //   padding: 9px 5px !important;
  // }
}

.canSeeWindow .el-form-item__label {
  font-size: 14px;
  color: #000000 !important;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
